package com.nl.deal;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nl.DealDataToSendMain;
import com.nl.redis.RedisCluster;
import com.nl.util.ConnectionManager;
import com.sun.tools.extcheck.Main;

public class ThresholdUpdate implements Runnable {
	private static final Logger log = LoggerFactory.getLogger(ThresholdUpdate.class);
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
	private SimpleDateFormat todaySdf = new SimpleDateFormat("yyyyMMdd");
	private Set<String> workPrograms = new HashSet<String>();
	private String workDay = "";
	private String redisCluster;
	private RedisCluster cluster;
	public ThresholdUpdate(String redisCluster) {
		this.redisCluster = redisCluster;
	}
	@Override
	public void run() {
		String updateSql = "update sms_realtime_control t set t.total_count=?,t.year_count=?," +
                "t.quarter_count=?,t.month_count=?,t.week_count=?,t.day_count=?," +
                "t.modify_time=sysdate where t.id=?";
        String updateStatusSql = "update sms_realtime_control t set t.status = 0 where t.id=?";
        log.info("Threshold update start");
		while(true) {
			try {
				Thread.sleep(1000);
				update(updateSql, updateStatusSql);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	private void update(String updateSql,String updateStatusSql) throws SQLException {
		if (!DealDataToSendMain.thresholdUpdateSuccess) {
			log.debug("threshold not update,wait");
			return;
		}
		
		 boolean isNextDay = false;
		 String today = todaySdf.format(new Date());
		 if ("".equals(workDay) || !today.equals(workDay)) {
			 workDay = today;
			 clean();
		 }
		 Map<String, ThresholdInfo> thresholdMapTmp = new HashMap<>();
		 Iterator<Map.Entry<String, ThresholdInfo>> it = DataCache.thresholdMap.entrySet().iterator();
		 while(it.hasNext()) {
			 Entry<String, ThresholdInfo> entry = it.next();
			 String mgrId = entry.getKey();
			 workPrograms.add(mgrId);		 
			 ThresholdInfo thresholdInfo = entry.getValue();
/*			 String compareToday = thresholdInfo.getToday();
			 log.debug(today+"####"+compareToday);
			 if (!today.equals(compareToday)) {
				 isNextDay = true;
				 break;
			 }*/
			 thresholdMapTmp.put(mgrId, thresholdInfo);
		 }
		 
		 if (isNextDay) {
			 log.info("time change,Next cycle update of threshold table!");
			 return;
		 }
		 
		 Map<String, Integer> mgrSendTmp = new HashMap<String, Integer>();
		 Iterator<Map.Entry<String, Integer>> itCount = DataCache.mgrSend.entrySet().iterator();
		 while(itCount.hasNext()) {
			 Entry<String, Integer> entryCount = itCount.next();
			 mgrSendTmp.put(entryCount.getKey(), entryCount.getValue());
		 }
		 
		 DataCache.mgrSend.clear();
		 log.debug("mgrSendTmp = "+mgrSendTmp);
		 
		 if (mgrSendTmp.isEmpty()) {
			 log.info("no data send, Next cycle update of threshold table!");
			 return;
		 }
		 Connection conn = ConnectionManager.getInstance().getConnection();
		 PreparedStatement pres = conn.prepareStatement(updateSql);
		 PreparedStatement statusPres = conn.prepareStatement(updateStatusSql);
		 for (String mgrId : thresholdMapTmp.keySet()) {
			 ThresholdInfo info = thresholdMapTmp.get(mgrId);
			 int incr = 0;
			 if (mgrSendTmp.containsKey(mgrId)) {
				 incr = mgrSendTmp.get(mgrId);
			 }
			 
			 try {
				
			} catch (Exception e) {
				// TODO: handle exception
			}
			 try {
				 cluster=new RedisCluster(redisCluster);
			} catch (Exception e) {
				log.info("new cluster exception :"+e.getMessage());
			}
			 //取redis中的实时发送量进行阀值更新操作
			 pres.setLong(1, Long.parseLong(cluster.get(mgrId+"totalCount")));
			 pres.setLong(2, Long.parseLong(cluster.get(mgrId+"yearCount")));
			 pres.setLong(3, Long.parseLong(cluster.get(mgrId+"quarterCount")));
			 pres.setLong(4, Long.parseLong(cluster.get(mgrId+"monthCount")));
			 pres.setLong(5, Long.parseLong(cluster.get(mgrId+"weekCount")));
			 pres.setLong(6, Long.parseLong(cluster.get(mgrId+"dayCount")));
//			 if (info.getThresholdStartTime() <= System.currentTimeMillis()
//	                    && info.getThresholdEndTime() >= System.currentTimeMillis()) {
//	                info.setTimeCount(info.getTimeCount() + incr);
//	         } else {
//	        	 pres.setLong(7, info.getTimeCount());
//	         }
//			 pres.setString(8, dealTime);
//			 pres.setString(8, "new_update_"+sdf.format(new Date()));
			 pres.setString(7, info.getMgrId());
			 pres.addBatch();

             if (info.getStatus() == 2) {
            	 statusPres.setString(1, info.getMgrId());
            	 statusPres.addBatch();
             }
         }
		 pres.executeBatch();
         statusPres.executeBatch();
         
         try {
			 if(null != cluster){
				 cluster.close();
			 }
		 } catch (IOException e) {
			 e.printStackTrace();
		 }
         
         if (null != pres) {
        	 pres.close();
         }
         
         if (null != statusPres) {
        	 statusPres.close();
         }
         
         if (null != conn) {
        	 conn.close();
         }
         log.info("update threshold successful!");
         DealDataToSendMain.thresholdUpdateSuccess = false;
	}
	
	
	private void clean() {
		try {
			if (!workPrograms.isEmpty()) {
				cluster = new RedisCluster(redisCluster);
				for (String mgrId: workPrograms) {
					try{
						cluster.del(mgrId);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				cluster.close();
				cluster = null;
			} else {
				log.info("no program clean!");
				return;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
